var exec = require('child_process').exec;
var fs = require('fs')
var axios = require('axios')
const { startCmd } = require('../services/exec');
const { requestGetWithAuth, requestPostWithAuth } = require("./mid_request");
const { url } = require('../../config/config');

var attachData = function(data, code, msg) {
    return {
        code: code,
        msg: msg,
        data: data,
    }
}

module.exports = {
    async update_function(name) {
        var cmd_update = `cd /root/usr_func && faas-cli up -f ./${name}.yml`
        return new Promise((resolve, reject) => {
            try {
                startCmd(cmd_update).then((e) => {
                    resolve(e);
                }).catch(e => {
                    resolve(e);
                })
            } catch (error) {
                resolve(error)
            }
        })
    },
    async new_by_dockerImg(image, function_name) {
        return new Promise((resolve, reject) => {
            var data = JSON.stringify({
                "image": image,
                "service": function_name,
                "envVars": {},
                "secrets": [],
                "labels": {},
                "annotations": {},
                "namespace": "openfaas-fn"
            });
            var config = {
                method: 'post',
                url: `http://${url}:31112/system/functions`,
                headers: {
                    'Authorization': 'Basic YWRtaW46YWRtaW4=',
                    'Content-Type': 'application/json'
                },
                data: data
            };
            axios(config)
                .then(function(response) {
                    resolve(JSON.stringify(response.data));
                })
                .catch(function(error) {
                    // console.log(error);
                    resolve(error);
                });
        })
    },
    async delete_node(name) {
        var data = `kubectl delete node ${name}`;
        return new Promise((resolve, reject) => {
            try {
                startCmd(data).then((e) => {
                    resolve(e);
                }).catch(e => {
                    resolve(e);
                })
            } catch (error) {
                resolve(error)
            }
        })
    },
    async delete_func(name) {
        var data = `{"functionName":"${name}"}`;
        var config = {
            method: 'delete',
            url: `http://${url}:31112/system/functions?namespace=openfaas-fn`,
            headers: {
                'Authorization': 'Basic YWRtaW46YWRtaW4=',
                'Content-Type': 'text/plain'
            },
            data: data
        };
        return new Promise((resolve, reject) => {
            axios(config)
                .then(function(response) {
                    resolve("删除成功！");
                })
                .catch(function(error) {
                    resolve(error);
                    console.log(error);
                });
        })
    },
    /**
     * name	nodeinfo	函数名称
     * files	[{
     *  "filename":"文件名",
     *  "filestream":"文件的文本流",
     * }]	上传的文件
     */
    async create_by_code(name, lang) {
        var ret_cmd = "";
        return new Promise((resolve, reject) => {
            requestGetWithAuth({ url: "/system/functions", data: {}, success: () => {} }).then(
                lists => {
                    lists.forEach((e) => {
                        if (name == e.name) {
                            resolve("已有重名的函数，创建失败")
                            return
                        }
                    })
                    var newFunc = `cd /root/usr_func && faas-cli new ${name} --lang ${lang || "node12"}`;
                    var changeProfile = `version: 1.0
provider:
    name: openfaas
    gateway: http://127.0.0.1:31112
functions:
    ${name}:
        lang: ${lang || "node12"}
        handler: ./${name}
        image: 127.0.0.1:5000/${name}:latest`;
                    var docker_up = `cd /root/usr_func && faas-cli up -f ./${name}.yml`;
                    startCmd(`rm -rf /root/usr_func/${name}.yml && rm -rf /root/usr_func/${name}`).then(exec_cmd => {
                        startCmd(newFunc).then((res) => {
                            ret_cmd += res;
                            fs.writeFile(`/root/usr_func/${name}.yml`, changeProfile, function(error) {
                                ret_cmd += error;
                                exec(docker_up, function(err, stdout, stderr) {
                                    ret_cmd += stdout;
                                    resolve(ret_cmd);
                                });
                            })
                        });
                    })
                });
        })
    },
    async get_addNew_cmd() {
        return new Promise((resolve, reject) => {
            exec("cat /var/lib/rancher/k3s/server/node-token", function(err, stdout, stderr) {
                var token = stdout;
                var cmd = "curl -sfL http://rancher-mirror.cnrancher.com/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn K3S_URL=https://" + url + ":6443 K3S_TOKEN=" + token + " sh -";
                console.log(attachData(cmd, 1, "获取新增节点命令成功！"));
                resolve(attachData(cmd, 1, "获取新增节点命令成功！"));
                if (err || stderr) {
                    console.log({ err, stderr });
                }
            });
        })
    },
    async get_sys_log() {
        return new Promise((resolve, reject) => {
            requestGetWithAuth({
                url: `/system/info`,
                contentType: "application/json",
                success: (res) => {
                    resolve(attachData(res, 1, "获取系统日志成功"));
                }
            })
        })
    },
    async get_active_function(func, data) {
        return new Promise((resolve, reject) => {
            requestGetWithAuth({
                url: `/system/function/${func}?namespace=openfaas-fn`,
                data: data,
                contentType: "application/json",
                success: (res) => {
                    res = {
                        name: res.name, //函数名称
                        invoke_count: 0, //调用的次数
                        status: res.availableReplicas, //0-未就绪 1-已就绪
                        run_time: Date.parse(new Date()) - Date.parse(new Date(res.createdAt)), //毫秒运行时间
                        images: res.image, //镜像的名称
                        url: `http://${url}:31112/function/${res.name}`, //调用的URL
                        invoke: `/root/usr_func/${res.name}/`, //调用函数的命令
                    };
                    resolve(attachData(res, 1, "获取目标函数成功"));
                }
            })
        })
    },
    async manual_invoke(func, data) {
        return new Promise((resolve, reject) => {
            console.log(`/function/${func}.openfaas-fn`);
            requestPostWithAuth({
                url: `/function/${func}.openfaas-fn`,
                data: data,
                contentType: "application/json",
                success: (res) => {
                    resolve(attachData(res, 1, "调用函数成功"));
                }
            })
        })
    },
    async openfaas_fn() {
        return new Promise((resolve, reject) => {
            requestGetWithAuth({
                url: "/system/functions",
                success: (res) => {
                    var data = res.map((e) => {
                        return {
                            name: e.name, //函数名称
                            invoke_count: e.invocationCount, //调用的次数
                            status: e.availableReplicas, //0-未就绪 1-已就绪
                            run_time: Date.parse(new Date()) - Date.parse(new Date(e.createdAt)), //毫秒运行时间
                            images: e.image, //镜像的名称
                            url: `http://${url}:31112/function/` + e.name, //调用的URL
                            invoke: `cd /root/usr_func/${e.name} && ls`, //调用函数的命令
                        }
                    });
                    resolve(attachData(data, 1, "获取函数总览成功"));
                }
            })
        })
    },
}